(function(){
	$.namespace("com.yogi.wrappers.basto");

	/**
	 * { "type":"basto_storesearch",
	  "data_url": "/flash/stores.txt" }
	 */
	com.yogi.wrappers.basto.StoreSearchWrapper = function() {
		com.yogi.wrappers.basto.StoreSearchWrapper.superclass.constructor.call(this);		
	};
	Ext.extend(com.yogi.wrappers.basto.StoreSearchWrapper,com.yogi.core.PartWrapperBase,{
		wrap: function(part,wrapperConfig,partConfig) {
			com.yogi.wrappers.basto.StoreSearchWrapper.superclass.wrap(part,wrapperConfig,partConfig);		
			
			var context = this;
			var m_config = false;	
			
			var combo_provinces  = false;
			var combo_cities = false;
			var div_details = false;
			var btn_search = false;

			function loadData() {
				var data_url = wrapperConfig.data_url;
				$.getJSON(data_url, function(data) {
					m_config = data;
					if(typeof data["BastoStores"] != 'undefined'){
						init();
					}else{				
						//console.log("configuration information load failed.");
						return;
					}
				});
			}
			function selectCity() {
				div_details.empty();
				var selectedCity = combo_cities.val();
				var allStores = m_config["BastoStores"];
				if(allStores != null){
					var storesBuffer = "<ul style='list-style: none outside none'>";
					var cnt = allStores.length;
					for(var i = 0;i < cnt; i++){
						var item = allStores[i];
						if(item["city"] == selectedCity){
							var stores = item["stores"];
							for(var j =0;j < stores.length;j++){
								storesBuffer += "<li>" + stores[j] + "</li>";
							}
							break;
						}
					}
					div_details.html(storesBuffer);
				}
			}
			function init() {
				combo_provinces = part.getElement("dp_provinces");
				combo_cities = part.getElement("dp_cities");
				var td_details = part.getElement("dp_details");
				div_details = $("<div></div>").appendTo(td_details);
				btn_search = part.getElement("btn_search");
				
				div_details.css({
					"overflow-y" : "auto",
					"text-align": "left",
					"height": (td_details.height() - 30)+ "px",
					"width": (td_details.width() - 30) + "px",
					"margin-bottom": "30px"
				});
				
				combo_provinces.change( function() {
					combo_cities.empty();
					div_details.empty();
					var province = $(this).val();
					var allCities = m_config["BastoCities"];
					var cnt = allCities.length;
					for(var i = 0;i < cnt;i++){
						var item = allCities[i];
						if(item["province"] == province){
							var cities = item["cities"];
							combo_cities.append("<option value=''>请选择城市</option>"); 
							if(cities.length > 0){
								for(var j = 0; j < cities.length; j++){
									combo_cities.append("<option value='" + cities[j] + "'>" + cities[j] + "</option>"); 
								}
							}
							break;
						}
					}
				});
				var allCities = m_config["BastoCities"];
				var cnt = allCities.length;
				combo_provinces.empty();
				combo_provinces.append("<option value=''>请选择省份</option>");
				for(var i = 0;i < cnt;i++){
					var item = allCities[i];
					combo_provinces.append("<option value='" + item["province"] + "'>" + item["province"] + "</option>"); 
				}
				combo_cities.empty();
				div_details.empty();
				btn_search.click(function() {
					selectCity();
				});
			}			
			part.waitForDiv(function(partComp){
				loadData();			
			});
		}
	});
	/**
	 * 
	{ 
			"type":"basto_care",
		 	"catalog":"2012HTML5BeautiTips_Fast",		//catalog names must be regulated
		 	"Components":{
		 		"title_ct": "Title_bg",
		 		"content_ct": "Content_bg",
		 		"title_previous":"btn_Previous",
		 		"title_next":"btn_next",
		 		"content_home":"Content_btn_back",
		 		"content_previous":"Content_btn_Previous",
		 		"content_next": "Content_btn_Next"	
		 	}
	 } 
	 */
	com.yogi.wrappers.basto.CareWrapper = function() {
		com.yogi.wrappers.basto.CareWrapper.superclass.constructor.call(this);		
	};
	Ext.extend(com.yogi.wrappers.basto.CareWrapper,com.yogi.core.PartWrapperBase,{
		wrap: function(part,wrapperConfig,partConfig) {
			com.yogi.wrappers.basto.CareWrapper.superclass.wrap(part,wrapperConfig,partConfig);		
			
			part.waitForDiv(function(partComp){
				var panel = new com.yogi.wrappers.basto.CarePanel(part,wrapperConfig);
				panel.init();
			});
		}
	});
	com.yogi.wrappers.basto.CarePanel = function(part,wrapperConfig) {
		var m_page_size = 2;
		var m_title_pages_ct = [];						//二维数组，一维对应标题分页，第二维是分页中的标题
		var m_content_pages_ct = {};				//内容div数组，key是title的index，二维是内容div数组
		var m_current_content_page = {};			//内容分页号，key是title的index, value 是title对应的内容的当前页号
		var m_current_title_index = 0;
		
		var m_title_stack = new com.yogi.runtime.PageStack();
		
		var m_titles_count;
		var m_title_pages_count = 0;
		var m_current_title_page = 0;
		
		var elements = {};
		
		function setupElements() {
			var element_ids = [ "title_ct","content_ct", "title_previous", "title_next", "content_home", "content_previous", "content_next" ];
			$.each(element_ids, function(idx, elem_id) {
				var elem = part.getElement(wrapperConfig["Components"][elem_id]);
				elements[elem_id] = $(elem);
				//m_pageStack.push(elem);
			});
			//console.log(elements);
			elements.title_next
				.css("cursor","pointer")
				.click( function() {
					if(m_current_title_page < m_title_pages_count - 1) {
						m_current_title_page ++;
						showTitlePage();
					}
			});
			elements.title_previous
				.css("cursor","pointer")
				.click( function() {
					if(m_current_title_page > 0) {
						m_current_title_page --;
						showTitlePage();
					}
			});
			elements.content_home
				.css("cursor","pointer")
				.click( function() {
					//return to title view
					showTitlePage();
			});
			elements.content_next
				.css("cursor","pointer")
				.click( function() {
					incrementContentIndex(true);
					showContent(m_current_title_index);
			});
			elements.content_previous
				.css("cursor","pointer")
				.click( function() {
					incrementContentIndex(false);
					showContent(m_current_title_index);
			});
		}
		function loadTitles() {
			// read information from catalog
			var title_images_js = window.contentPanel.getVirDir() + "yogi/config/" + wrapperConfig.catalog + "/json.js";
			//console.log(title_images_js);
			$.getScript(title_images_js, function(script,textStatus) {
				if(textStatus != "success") {
					throw "loading script:" + title_images_js + " error.";
				}	
				//console.log("images_data=");
				//console.log(images_data);
				var title_images_toload = [];
				for(var i=0;i < images_data.length; i++){
					//console.log(images_data[i]);
					var ImageUrl = images_data[i].ImageUrl;
					//console.log(ImageUrl);
					title_images_toload.push(ImageUrl);										
				}
				if(title_images_toload.length > 0) {					
					window.contentPanel.loadResources(title_images_toload, onTitleImagesLoaded);
				}
			});			
		}
		function onTitleImagesLoaded(images_urls) {
			window.contentPanel.hideLoadingIcon();
			m_titles_count = images_urls.length;
			m_title_pages_count = Math.ceil(m_titles_count / m_page_size);
			//把各标题页倒序按两个一页归并
			var c = m_titles_count-1;
			for(var i =0;i < m_title_pages_count;i++){
				if(c < 0) { break; }
				var ct = [];
				m_title_pages_ct.push(ct);
				for(var j =0;j < m_page_size; j++) {
					if(c >= 0) {
						var mc = $("<div class='title_" + c + "'><img src='" + images_urls[c] + "' /></div>");
						ct.push(mc);
					}
					c--;		//消耗一个标题
				}				
			}		
			showTitlePage();
		}
		function onTitleClicked() {
			var title_index = $(this).data("index");
			m_current_title_index = title_index;
			//console.log("onTItleClicked:title_index=" + title_index);
			if(m_content_pages_ct[title_index]) {			//already has content stored
				showContent( title_index );
			} else {
				var content_images_js = window.contentPanel.getVirDir() + "yogi/config/" + wrapperConfig.catalog + "_Title" + (title_index+1) + "/json.js";
				//console.log(content_images_js);
				$.getScript(content_images_js, function(script,textStatus) {
					if(textStatus != "success") {
						throw "loading script:" + content_images_js + " error.";
					}
					var images_toload = [];
					for(var i=0;i < images_data.length; i++){
						var ImageUrl = images_data[i].ImageUrl;
						images_toload.push(ImageUrl);										
					}
					if(images_toload.length > 0) {
						window.contentPanel.loadResources(images_toload, function(urls) {
							window.contentPanel.hideLoadingIcon();
							var content_pages = [];
							$.each(urls, function(i, url) {
								var mc = $("<div><img src='" + url + "' /></div>");
								content_pages.push(mc);
							});
							m_content_pages_ct[title_index] = content_pages;
							showContent( title_index );
						});
					}	
				});
			}
		}
		function showContentElements(show) {	
			//console.log(elements);
			$.each(["content_ct","content_home", "content_previous", "content_next"], function(i, elem) {
				var e = elements[elem];
				if(show) e.show().css("opacity","1");
				else e.hide();
			});
		}
		function showTitleElements(show) {
			$.each(["title_ct","title_next","title_previous"], function(i, elem) {
				if(show) {
					elements[elem].show().css("opacity","1");					
				}
				else elements[elem].hide();
			});
			if(show) {
				if(m_current_title_page == 0) {
					elements.title_next.show();
					elements.title_previous.hide();
				}
				if(m_current_title_page == m_title_pages_count - 1){
					elements.title_next.hide();
					elements.title_previous.show();
				}	
			}
		}
		function getCurrentContentIndex(title_index) {
			//console.log("getCurrentContentIndex:m_current_content_page=" + m_current_content_page);
			//console.log(m_current_content_page);
			var content_page_index = m_current_content_page[title_index];
			if( typeof(content_page_index) == 'undefined') {
				content_page_index = 0;
				m_current_content_page[title_index] = content_page_index;
			}
			return content_page_index;
		}
		function incrementContentIndex(inc) {
			var content_page_index = getCurrentContentIndex(m_current_title_index);
			//console.log("incrementContentIndex:" + content_page_index );
			if(inc) {
				if(content_page_index < m_content_pages_ct[m_current_title_index].length - 1) {
					m_current_content_page[m_current_title_index] = content_page_index + 1;
					return true;
				}
			} else {
				if( content_page_index > 0) {
					m_current_content_page[m_current_title_index] = content_page_index - 1;
					return true;
				}
			}
			return false;
		}
		function getCurrentContentPage(title_index) {
			//console.log("getCurrentContentPage:");
			//console.log(m_content_pages_ct);
			var content_page_index = getCurrentContentIndex(title_index);
			//console.log("title_index=" + title_index + ",content_page_index=" + content_page_index);
			var content_div = m_content_pages_ct[title_index][content_page_index];
			return content_div;
		}
		function showContent(selected_title_index) {
			showContentElements(true);
			showTitleElements(false);
			elements.content_ct.empty();
			elements.content_ct.hide();
			
			var content_div = getCurrentContentPage( selected_title_index); 
			elements.content_ct.append(content_div);
			elements.content_ct.fadeIn('slow');
		}
		function showTitlePage() {	
			showContentElements(false);
			showTitleElements(true);			
			
			elements.title_ct.empty();
			elements.title_ct.hide();
			var title_page = m_title_pages_ct[m_current_title_page];
			$.each(title_page, function(i, div) {
				elements.title_ct.append(div);
				div.css("cursor","pointer")
					.data("index", m_current_title_page * m_page_size + i)
					.click( onTitleClicked );
				if(i < title_page.length - 1) {
					//append a vertical gap
					elements.title_ct.append("<div style='height=50px'>&nbsp;</div>");
				}
			});			
			elements.title_ct.fadeIn('slow');
		}
		var self = {
				init: function() {
					setupElements();
					loadTitles();
				}
		};
		return self;
	};
	
	var wrapperManager = window.contentPanel.getWrapperManager();
	wrapperManager.registerWrapperClass("basto_storesearch", com.yogi.wrappers.basto.StoreSearchWrapper);
	wrapperManager.registerWrapperClass("basto_care", com.yogi.wrappers.basto.CareWrapper);
})();